package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.ShotManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskConfig;
import cc.ufinity.networkdiagnose.manager.Task.FTPTask;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TaskResult extends GeneralTestWidget {

    private LinearLayout httptaskLayout;
    private LinearLayout ftptaskLayout;
    private LinearLayout pingtaskLayout;

    private LinearLayout aptaskLayout;
    private LinearLayout webauthtaskLayout;
    private LinearLayout isolateLayout;
    private LinearLayout roamLayout;

    private LinearLayout aptaskTitleLayout;
    private LinearLayout webauthtaskTitleLayout;
    private LinearLayout isolateTitlteLayout;
    private LinearLayout roamTitleLayout;

    private Activity ctx;
    private Task task;
    private Button backBtn;
    private Button btnDraw;
    private LinearLayout taskNumLayout;
    private Handler handler;
    private String fileName;
    private Button btnPic;

    public TaskResult(Activity context) {
        super(context);
        inflate(context, R.layout.task_result_widget, this);
        this.ctx = context;
        httptaskLayout = (LinearLayout) this.findViewById(R.id.httpTaskFinishLayout);
        ftptaskLayout = (LinearLayout) this.findViewById(R.id.ftpTaskFinishLayout);
        pingtaskLayout = (LinearLayout) this.findViewById(R.id.pingTaskFinishLayout);

        aptaskLayout = (LinearLayout) this.findViewById(R.id.apTaskFinishLayout);
        webauthtaskLayout = (LinearLayout) this.findViewById(R.id.webauthTaskFinishLayout);
        isolateLayout = (LinearLayout) this.findViewById(R.id.isolateTaskFinishLayout);
        roamLayout = (LinearLayout) this.findViewById(R.id.roamTaskFinishLayout);

        aptaskTitleLayout = (LinearLayout) this.findViewById(R.id.apTaskLayoutTitle);
        webauthtaskTitleLayout = (LinearLayout) this.findViewById(R.id.webauthTaskLayoutTitle);
        isolateTitlteLayout = (LinearLayout) this.findViewById(R.id.isolateTaskLayoutTitle);
        roamTitleLayout = (LinearLayout) this.findViewById(R.id.roamTaskLayoutTitle);

        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        taskNumLayout = (LinearLayout) this.findViewById(R.id.taskNumLayout);
        backBtn = (Button) this.findViewById(R.id.task_result_btnBack);
        btnDraw = (Button) this.findViewById(R.id.btn_draw);
        btnPic = (Button)this.findViewById(R.id.btnpic);
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });
        btnPic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                CameraWidget cw = new CameraWidget(ctx);
                ctx.setContentView(cw);
            }
        });
        btnDraw.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != fileName) {
                    showMessage(ctx, "正在重新上传中...");
                    new Thread() {
                        public void run() {
                            if (uplod(fileName, ctx, handler))
                                fileName = null;
                        }
                    }.start();
                } else {
                    showMessage(ctx, "文件已上传或未进行测试.");
                }
                // shotScreen();
            }
        });
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                }
            }
        };
        upload();
    }

    private void shotScreen() {
        ShotManager sm = new ShotManager(ctx);
        Bitmap bm = sm.shot();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmsss");
        Date curDate = new Date(System.currentTimeMillis());
        final String fileName = formatter.format(curDate) + ".jpg";

        File file = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
        } catch (FileNotFoundException e) {
            Log.e("TaskResult", "截屏出错：", e);
            this.showMessage(ctx, "截屏失败.");
            return;
        }
        showMessage(ctx, "正在上传截屏...");
        new Thread() {
            public void run() {
                uplod(fileName, ctx, handler);
            }
        }.start();
    }

    private void upload() {
        createResultXML();
        show();
    }

    private void createResultXML() {
        task.endTime = StringUtils.getDateTime();
        TaskParser parser = new PullTaskParser();
        fileName = parser.XmlFileCreator(task);
        ctx.getIntent().putExtra("xml", fileName);
        DBManager db = new DBManager(ctx);
        db.saveTask(task.mac, task.apName, String.valueOf(task.id));
        db.release();
        if (null != fileName) {
            showMessage(ctx, "正在上传测试结果...");
            new Thread() {
                public void run() {
                    if (uplod(fileName, ctx, handler))
                        fileName = null;
                }
            }.start();
        }
        ctx.getIntent().removeExtra(TAG_REFER_TASK);
    }

    private void show() {
        DecimalFormat df = new DecimalFormat("#0.000");
        StringBuffer s = new StringBuffer();
        List<HttpTask> httpTasks = task.httpTasks;
        int size = httpTasks.size();
        float delay = 0;
        float speed = 0;
        int failedTimes = 0;
        for (HttpTask task : httpTasks) {
            delay += StringUtils.parseFloat(task.delay);
            speed += StringUtils.parseFloat(task.speed);
            failedTimes += task.failedTimes;
        }
        float avgDelay = (float) delay / size;
        float avgSpeed = (float) speed / size;
        float avgSuccess = ((float) (size * task.testCount - failedTimes) / (size * task.testCount)) * 100;
        // ((float)(num*task.testCount - failedTimes)/(num*task.testCount))*100;

        s.append("平均时延：").append(df.format(avgDelay)).append(" s;").append('\n');
        s.append("访问成功率：").append(avgSuccess).append(" %");
        TextView t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        httptaskLayout.addView(t);

        List<FTPTask> ftpTasks = task.ftpTasks;
        size = ftpTasks.size();
        long loginTime = 0;
        float dwrate = 0, upRate = 0;
        for (FTPTask task : ftpTasks) {
            loginTime += task.loginTime;
            dwrate += StringUtils.parseFloat(task.downRate);
            upRate += StringUtils.parseFloat(task.upRate);
        }
        float avgDwRate = (float) upRate / size;
        float avgUpReate = (float) dwrate / size;
        float avgLoginTime = (float) ((float) (loginTime / 1000) / size);
        s = new StringBuffer();
        s.append("平均上传速度：").append(df.format(avgDwRate)).append(" kb/s;").append('\n');
        s.append("平均下载速度：").append(df.format(avgUpReate)).append(" kb/s;").append('\n');
        s.append("上传成功率：").append("100").append(" %;").append('\n');
        s.append("下载成功率：").append("100").append(" %;");
        // s.append("平均登录时延：").append(df.format(avgLoginTime)).append(" s;");
        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        ftptaskLayout.addView(t);

        float time = 0, ttl = 0, bytes = 0;
        List<PingTask> pingTasks = task.pingTasks;
        size = ftpTasks.size();
        for (PingTask task : pingTasks) {
            time += StringUtils.parseFloat(task.time);
            ttl += StringUtils.parseFloat(task.ttl);
            bytes += StringUtils.parseFloat(task.bytes);
        }
        float avgTime = (float) time / size;
        float avgTTL = (float) ttl / size;
        float avgBytes = (float) bytes / size;
        s = new StringBuffer();
        s.append("平均时延：").append(df.format((float) avgTime / 1000)).append(" s;").append('\n');
        s.append("丢包率：").append("0").append(" %;");
        // s.append("Bytes：").append(df.format(avgBytes)).append(" byte;");
        t = new TextView(ctx);
        t.setTextColor(Color.WHITE);
        t.setText(s);
        pingtaskLayout.addView(t);

        if (task.selNetType == ConnectivityManager.TYPE_WIFI) {
            aptaskTitleLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            s.append("平均关联时间：").append(task.relevanceAPAvgTime).append("s;").append('\n');
            s.append("关联成功率：").append(task.relevanceAPSuccessRate).append("%;");
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            aptaskLayout.addView(t);

            webauthtaskTitleLayout.setVisibility(VISIBLE);
            s = new StringBuffer();
            s.append("平均认证时间：").append(task.webDelay).append("s;").append('\n');
            s.append("认证成功率：").append(task.webSuccessRate).append("%;").append('\n');
            s.append("下线成功率：").append(task.webOffSuccessRate).append("%;");
            t = new TextView(ctx);
            t.setTextColor(Color.WHITE);
            t.setText(s);
            webauthtaskLayout.addView(t);

            if (Task.TASK_TYPE_Y.equals(task.taskType)) {
                isolateTitlteLayout.setVisibility(VISIBLE);
                s = new StringBuffer();
                s.append("隔离成功率：").append(task.userIsolateSuccessRate).append("%;");
                t = new TextView(ctx);
                t.setTextColor(Color.WHITE);
                t.setText(s);
                isolateLayout.addView(t);

                roamTitleLayout.setVisibility(VISIBLE);
                s = new StringBuffer();
                s.append("漫游成功率：").append(task.userRoamSuccessRate).append("%;");
                t = new TextView(ctx);
                t.setTextColor(Color.WHITE);
                t.setText(s);
                roamLayout.addView(t);
            }
        }

        showTaskNum();
    }

    private void showTaskNum() {
        int infoSize = ctx.getIntent().getIntExtra("info", 0);
        if (infoSize > 0) {
            DBManager db = new DBManager(ctx);
            List<TaskConfig> configs = db.getTask(task.apName, String.valueOf(task.id));
            db.release();
            StringBuffer s = new StringBuffer();
            s.append("已完成此热点下  ").append(configs.size()).append(" 项测试.");
            s.append("还剩 ").append(infoSize - configs.size()).append(" 项.");
            TextView tv = new TextView(ctx);
            tv.setText(s);
            tv.setTextSize(14);
            tv.setTextColor(Color.CYAN);
            taskNumLayout.addView(tv);
        }
    }
}
